package com.lynn.cons.service;

import com.lynn.cons.data.CloudDataService;
import com.lynn.cons.data.ConsDataService;
import com.lynn.cons.model.em.E_Cons;
import com.lynn.cons.widget.controller.FormController;
import com.lynn.cons.widget.controller.FormControllerManager;
import ohos.aafwk.ability.Ability;
import ohos.aafwk.content.Intent;
import ohos.rpc.IRemoteObject;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;

import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

public class ServiceAbility extends Ability {
    private static final HiLogLabel LABEL_LOG = new HiLogLabel(3, 0xD001100, "Demo");
    private static final long UPDATE_DATA = 1000L * 300;
    private static final long UPDATE_FORM = 1000L * 300;

    @Override
    public void onStart(Intent intent) {
        HiLog.error(LABEL_LOG, "ServiceAbility::onStart");
        getData();
        startGetData();
        super.onStart(intent);
    }

    @Override
    public void onBackground() {
        super.onBackground();
        HiLog.info(LABEL_LOG, "ServiceAbility::onBackground");
    }

    @Override
    public void onStop() {
        super.onStop();
        HiLog.info(LABEL_LOG, "ServiceAbility::onStop");
    }

    @Override
    public void onCommand(Intent intent, boolean restart, int startId) {
    }

    @Override
    public IRemoteObject onConnect(Intent intent) {
        return null;
    }

    @Override
    public void onDisconnect(Intent intent) {
    }

    private void startGetData() {
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                //调度内容
                getData();
            }
        }, 0, UPDATE_DATA);
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                //调度内容
                updateForm();
            }
        }, 0, UPDATE_FORM);
    }

    private void getData() {
        CloudDataService service = CloudDataService.getInstance();
        ConsDataService dataService = ConsDataService.getInstance();
        service.getCalendarByDays(5, calends -> {
        });
        E_Cons cons = dataService.getUserCon();
        service.getConsFortune(cons.getIndex(), 1, res -> {
        });
    }

    private void updateForm() {
        FormControllerManager formControllerManager = FormControllerManager.getInstance(this);
        if (formControllerManager == null) return;
        List<Long> formList = formControllerManager.getAllFormIdFromSharePreference();
        for (long formId : formList) {
            FormController controller = formControllerManager.getController(formId);
            if (controller == null) continue;
            controller.updateFormData();
        }
    }
}